<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-02-22 10:43:19
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
  <div class="alarmDefinition">
    <!-- <nutbTitle title="指令查询"></nutbTitle> -->
    <NuVerifyForm :model="formData" ref="formData" label-width="100px" class="searchForm" @searchForm="searchForm"
      :buttons="fyButtons">
      <NuformItem label="指令类型" prop="cmdType" width="320px">
        <nu-select class="searchSelect" :filterable="true" :list="cmdTypeList" type="text" v-model="formData.cmdType"
          autocomplete="off" @change="cmdTypeChange" style="width: 100%" placeholder="请选择" clearable>
        </nu-select>
      </NuformItem>
      <NuformItem label="指令对象" prop="deviceName" width="320px">
        <nu-input type="text" v-model="formData.deviceName" size="middle" placeholder="请输入"></nu-input>
      </NuformItem>
      <NuformItem label="时间" prop="date" width="520px">
        <el-date-picker v-model="formData.date" type="datetimerange" style="width: 100%"
          value-format="yyyy-MM-dd HH:mm:ss" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </NuformItem>
      <NuformItem label="通道组" prop="channelGroupId" width="320px">
        <nu-select class="searchSelect" :filterable="true" :list="channelGroup" type="text"
          v-model="formData.channelGroupId" autocomplete="off" @change="channelChange" style="width: 100%"
          placeholder="请选择">
        </nu-select>
      </NuformItem>
      <NuformItem label="通道" prop="channelId" width="320px">
        <nu-select class="searchSelect" :filterable="true" :list="channelCondition" type="text"
          v-model="formData.channelId" autocomplete="off" @change="thoroughChange" style="width: 100%" placeholder="请选择">
        </nu-select>
      </NuformItem>
      <div class="btnBox">
        <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
        <nu-button class="searchButton" @click="clearParams">清除</nu-button>
      </div>
    </NuVerifyForm>
    <div class="line"></div>
    <div style="height: 35px; position: relative; padding: 0 10px" class="renovateTime">
      <nu-button class="searchButton" @click="exportTable">导出</nu-button>
      <nu-button class="searchButton" v-print="printOption">打印</nu-button>
    </div>
    <!-- <nutbTitle title="指令列表"></nutbTitle> -->
    <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
      :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
      @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange">
    </NuTableList>
    <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="optionsPrint"
      style="position: absolute;left: -5000px;z-index: -100;opacity: 0;">
    </NuTableList>
    <!-- </nu-col> -->
    <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="40%" center :close-on-click-modal="false" top="5vh"
      :modal-append-to-body="false" @close="diaClose">
      <div class="dialogHeaderSearch">
        <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="100px" class="submitForm"
          @submitForm="diaSubmitForm" :buttons="fyButtons">
          <NuformItem label="指令id" prop="cmdId" width="70%">
            <nu-input type="text" v-model="dialogFormData.cmdId" size="middle" :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="指令类型" prop="cmdType" width="70%" :rules="[{ required: false, message: '设备类型不能为空' }]">
            <nu-input type="text" v-model="dialogFormData.cmdType" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="指令对象" prop="relatedDevName" width="70%" :rules="[{ required: false, message: '设备类型不能为空' }]">
            <nu-input type="text" v-model="dialogFormData.relatedDevName" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="指令值" prop="cmdValue" width="70%" :rules="[{ required: false, message: '设备类型不能为空' }]">
            <nu-input type="text" v-model="dialogFormData.cmdValue" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="单位" prop="unit" width="70%" :rules="[{ required: false, message: '设备类型不能为空' }]">
            <nu-input type="text" v-model="dialogFormData.unit" size="middle" :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="指令时间" prop="cmdTime" width="70%">
            <nu-input type="text" v-model="dialogFormData.cmdTime" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="通道组" prop="channelGroupName" width="70%">
            <nu-input type="text" v-model="dialogFormData.channelGroupName" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
          <NuformItem label="通道" prop="adaptChannelName" width="70%">
            <nu-input type="text" v-model="dialogFormData.adaptChannelName" size="middle"
              :disabled="dialogFormDisabled"></nu-input>
          </NuformItem>
        </NuVerifyForm>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave" v-if="dialogTitle == '编辑'">保存</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave" v-if="dialogTitle == '新增'">新增</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaClose">关闭</nu-button>
      </div>
    </nu-dialog>
    <nu-dialog :title="upload.title" :visible.sync="upload.open" width="30%" center :close-on-click-modal="false"
      top="5vh" :modal-append-to-body="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.data" name="file">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                                                                                @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </nu-dialog>
  </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuDialog from "@/components/base/dialog";
import axios from "axios";
const operates = (that) => [
  // {
  //     label: '编辑',
  //     icon: '',
  //     width: '50px',
  //     isShow: row => {
  //         return true;
  //     },
  //     disabled: row => {
  //         return false;
  //     },
  //     method: row => {
  //         that.openEdit(row);
  //     },
  // },
  {
    isShow: (row) => {
      return false;
    },
  },
  {
    label: "查看",
    icon: "",
    width: "100px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.openDetail(row);
    },
  },
  // {
  //     label: '删除',
  //     icon: '',
  //     width: '50px',
  //     isShow: row => {
  //         return true;
  //     },
  //     disabled: row => {
  //         return false;
  //     },
  //     method: row => {
  //         that.tbRowdetele(row);
  //     },
  // },
];
import { getToken } from "@/utils/auth";
export default {
  name: "alarmDefinition",
  components: {
    nuCol,
    nutbTitle,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuDialog,
  },
  data() {
    return {
      formData: {
        channelGroupId: "",
        channelId: "",
        date: [],
        cmdType: "",
        deviceName: ""
      },
      dialogFormData: {},
      fyButtons: [],
      operates,
      currentRow: null,
      pagination: {
        pageSize: 20,
        total: 0,
        pageNum: 1,
      },
      dialogTitle: "",
      dialogShow: false,
      cmdTypeList: [],
      channelCondition: [],
      channelGroup: [],
      channelConditionMap: [],
      columns: [
        {
          label: "序号",
          prop: "ranking",
          width: "70px",
          render: (h, params) => {
            return h(
              "span",
              params.index +
              1 +
              (this.pagination.pageNum - 1) * this.pagination.pageSize
            );
          },
        },
        {
          label: "指令id",
          prop: "cmdId",
        },
        {
          label: "指令类型",
          prop: "cmdType",
          width: 200
        },
        {
          label: "指令对象",
          prop: "relatedDevName",
        },
        {
          label: '点号',
          prop: 'ioa',
        },
        {
          label: "指令值",
          prop: "cmdValue",
        },
        {
          label: '单位',
          prop: 'unit',
        },
        {
          label: "指令时间",
          prop: "cmdTime",
          width: 170
        },
        {
          label: "通道组",
          prop: "channelGroupName",
        },
        {
          label: "通道",
          prop: "adaptChannelName",
        },
      ],
      dataSource: [{}],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        height: "calc(100vh - 310px)",
        props: {
          fixed: "right",
        },
      },
      optionsPrint: {
        'row-key': 'pid',
        height: '100vh',
        tId: 'multipleTable',
        style: 'width:1000px'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + window.api.importAlarmDefinition,
        // 上传时附带的额外参数
        data: { id: 1 },
      },
      printOption: {
        id: "multipleTable",
        preview: true,
        previewTitle: "预览",
        popTitle: "",
        extraHead: "",
        extraCss: `<meta http-equiv='Content-Language' content='zh-cn'/>`
      },
    };
  },
  computed: {
    dialogFormDisabled() {
      return this.dialogTitle == "详情";
    },
  },
  created() {
    this.getInstructTypeData();
    this.getChannelGroupSet();
    this.getChannelCondition();
  },
  mounted() {
    this.getAlarmDefinition();

  },
  methods: {
    /**
     * 查询
     */
    searchTable() {
      this.$refs["formData"].searchForm("form");

    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getAlarmDefinition();
      }
    },
    /**
     * 获取指令类型数据项
     */
    getInstructTypeData() {
      this.getCategoryDicts('COMMAND').then(data => {
        let newData = data.map(item => {
          return { label: item.dictName, value: item.dictName }
        })
        this.cmdTypeList = newData
      })
    },
    /**
     * 获取通道组数据项
     */
    getChannelGroupSet() {
      let postData = {
        pageSize: 9999,
        pageNum: 1,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getChannelGroupSet, postData).then((res) => {
        if (res.code == 200 && res.rows) {
          res.rows.map((item) => {
            this.channelGroup.push({
              label: item.groupName,
              value: item.id,
            });
          });
        } else {
        }
      });
    },
    /**
     * 获取通道数据项
     */
    getChannelCondition() {
      let postData = {
        channelName: "",
        pageSize: 9999,
        pageNum: 1,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getChannelCondition, postData).then((res) => {
        if (res.code == 200 && res.rows) {
          this.channelCondition = []
          this.channelConditionMap = res.rows
        } else {
        }
      });
    },
    /**
     * change事件
     */
    cmdTypeChange() { },
    /**
     * change事件
     */
    thoroughChange() { },
    /**
     * 通道组change事件
     */
    channelChange(val) {
      let a = []
      this.channelCondition = []
      a = this.channelConditionMap.filter(item => item.belongGroupId == val)
      a.map((item) => {
        this.channelCondition.push({
          label: item.channelName,
          value: item.channelId,
        });
      });
      this.formData.channelId = ''
    },
    /**
     * 新增
     */
    addTable() {
      this.dialogTitle = "新增";
      this.dialogShow = true;
    },
    /**
     * 导入
     */
    importTable() {
      this.upload.title = "设备表导入";
      this.upload.open = true;
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(val) {
      this.pagination.pageNum = 1;
      this.pagination.pageSize = val;
      this.getAlarmDefinition();
    },
    /**
     * 改变分页触发事件
     */
    handleChangePage(val) {
      this.pagination.pageNum = val;
      this.getAlarmDefinition();
    },
    /**
     * 表格-编辑
     */
    openEdit(row) {
      this.dialogTitle = "编辑";
      this.dialogShow = true;
      Object.assign(this.dialogFormData, row);
    },
    /**
     * 表格-详情
     */
    openDetail(row) {
      this.dialogTitle = "详情";
      this.dialogShow = true;
      Object.assign(this.dialogFormData, row);
    },
    /**
     * 表格-删除
     */
    tbRowdetele(row) {
      this.$confirm("确定要删除设备【" + row.name + "】吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delElectricityMeter(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * dialogFormData组件内置提交事件
     */
    diaSubmitForm(val) {
      if (val) {
        if (this.dialogTitle == "编辑") {
          this.editAlarmDefinition();
        } else if (this.dialogTitle == "新增") {
          this.addAlarmDefinition();
        }
      }
    },
    /**
     * 弹窗-保存
     */
    diaSave() {
      this.$refs["dialogFormData"].submitForm("form");
    },
    /**
     * 弹窗-关闭
     */
    diaClose() {
      this.dialogShow = false;
      this.resetForm("dialogFormData");
    },
    /**
     * 清除数据
     */
    clearParams() {
      this.resetForm("formData");
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = "";
        }
      }
    },
    /**
     * 导出
     */
    exportTable() {
      let postData = {
        ...this.formData,
        startDay: this.formData.date[0],
        endDay: this.formData.date[1],
      };
      delete postData.date
      this.getDownload(window.api.exportSignalCommands, {
        ...postData
      }, `指令记录信息.xlsx`)
    },
    /**
     * 获取表格数据
     */
    getAlarmDefinition() {
      let postData = {
        ...this.formData,
        ...this.pagination,
        startDay: this.formData.date[0],
        endDay: this.formData.date[1],
      };
      delete postData.date
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.dataSource = [];
      this.$httpGet(window.api.getAlarmDefinition, postData)
        .then((res) => {
          if (res.code && res.rows) {
            this.pagination.total = res.total;
            this.dataSource = res.rows;
            this.diaClose();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 单选
     */
    handleCurrentChange(val) {
      this.currentRow = val;
      console.log(this.currentRow);
    },
    /**
     * 编辑接口
     */
    editAlarmDefinition() {
      let postData = {
        ...this.dialogFormData,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPost(window.api.editAlarmDefinition, postData)
        .then((res) => {
          if (res.success) {
            this.$message({
              message: "成功",
              type: "success",
            });
            this.getAlarmDefinition();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 删除表格数据
     */
    delElectricityMeter(row) {
      let postData = {
        id: row.id,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.dataSource = [];
      this.$httpPost(window.api.delAlarmDefinition, postData)
        .then((res) => {
          if (res.success) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getAlarmDefinition();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 新增接口
     */
    addAlarmDefinition() {
      let postData = {
        ...this.dialogFormData,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPost(window.api.addAlarmDefinition, postData)
        .then((res) => {
          if (res.success) {
            this.$message({
              message: "成功",
              type: "success",
            });
            this.getAlarmDefinition();
          } else {
          }
        })
        .catch((err) => { });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$message({
        message: response.message,
        type: "success",
      });
      this.searchTable();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /**
     * 模糊搜索某类字典数据(如：指令)
     * @param {*} type 
     */
    getCategoryDicts(type) {
      return new Promise((resolve, reject) => {
        this.$httpGet(window.api.getCategoryDicts, { dictTypeText: type })
          .then((res) => {
            if (res.code && res.rows) {
              resolve(res.rows)
            } else {
            }
          })
          .catch((err) => { });
      })
    }
  },
};
</script>
    
<style scoped lang="scss">
.alarmDefinition {
  height: 100%;
}

.searchForm {
  // height: calc(100% - 40px);
  display: flex;
  position: relative;
  flex-wrap: wrap;
  padding-right: 160px;
}

.submitForm {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.btnBox {
  display: flex;
  // float: right;
  z-index: 10;
  position: absolute;
  // top: 15px;
  right: 10px;
  margin: 10px 0 0 0;
}

.dialogHeaderSearch {
  background-color: var(--model-bgc);
  padding: 10px;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: right;
}

::v-deep .el-upload {
  width: 100%;

  .el-upload-dragger {
    width: auto;
  }
}
</style>